package main.java;

import java.awt.*;

public class Bullet {
    private int x, y;
    private static final int SPEED = Integer.parseInt((String)PropertiesMgr.get("bulletSpeed"));
    private Dir dir;
    private Group group;
    private TankFrame tf = null;

    Rectangle rect = new Rectangle();

    public boolean isAlive() {
        return isAlive;
    }

    private boolean isAlive = true;

    public static final int WIDTH = ResourceMgr.getInstance().getBulletD().getWidth();
    public static final int HEIGHT = ResourceMgr.getInstance().getBulletD().getHeight();

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Dir getDir() {
        return dir;
    }

    public void setDir(Dir dir) {
        this.dir = dir;
    }



    public Bullet(int x, int y, Dir dir, Group group, TankFrame tf) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tf = tf;
        rect.x = x;
        rect.y = y;
        rect.width = WIDTH;
        rect.height = HEIGHT;
        tf.bullets.add(this);
    }

    public void paint(Graphics g) {
        move();
        Image image = null;
        switch (dir) {
            case UP:
                image = ResourceMgr.getInstance().getBulletU();
                break;
            case DOWN:
                image = ResourceMgr.getInstance().getBulletD();
                break;
            case LEFT:
                image = ResourceMgr.getInstance().getBulletL();
                break;
            case RIGHT:
                image = ResourceMgr.getInstance().getBulletR();
                break;
        }
        g.drawImage(image, x, y,null);
    }

    private void move() {
        switch (dir) {
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
        }
        rect.x = x;
        rect.y = y;
    }

    public void collideWith(Tank tank) {
        if(this.group == tank.getGroup()) return;
        if(tank.getRect().intersects(rect)){
            tank.die();
            this.die();
            int eX = tank.getX() + Tank.WIDTH / 2 - Explode.WIDTH / 2;
            int eY = tank.getY() + Tank.HEIGHT / 2 - Explode.HEIGHT / 2;
            tf.explodes.add(new Explode(eX, eY, tf));
        }
    }

    private void die() {
        this.isAlive = false;
    }
}
